package com.ebt.m.customer.util;

import android.content.Context;

import com.ebt.m.customer.db.CustomerInteraction;
import com.ebt.m.customer.db.InteractionUtil;
import com.ebt.m.customer.listener.ICustomer;
import com.ebt.m.data.CustomerData;
import com.ebt.m.data.greendao.CustomerInteractionDao;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class CustomerRecorder {
	public static final String TAG = "CustomerRecorder";
	public static final int CUSTOMER_ADDED = 1;//添加客户
	//public static final int CUSTOMER_EDITED = 2;//编辑客户

	public static final int ATTACHMENT_ADDED = 2;//添加附件
	public static final int NOTE_ADDED = 3;//添加笔记

    public static final int CUSTOMER_ADDED_INTO_ONE_RECORD = 7;//添加客户

    public static final int CUSTOMER_IMPORT_INTO_RECORDS = 9;//导入客户时添加单条记录
	/**
	 * 用于记录动态
	 * @param context
	 * @param iCustomers
	 * @param state
	 * @param description
	 */
	public static <E> void recordCustomers(Context context, ArrayList<E> iCustomers, int state, String description){
		
		long now = System.currentTimeMillis();
		InteractionUtil util = InteractionUtil.getInstance(context);
        String userIdentity = String.valueOf(CustomerData.getCurrentUserIdentity());
		for(E iCustomer : iCustomers){
		
			CustomerInteraction interaction = new CustomerInteraction();
			interaction.setDescription(description);
			interaction.setUpdateTime(now);
			interaction.setCategory(state);
            interaction.setUserIdentity(userIdentity);
			interaction.setCustomerUuid(((ICustomer) iCustomer).getCustomerUuid());
			interaction.setUuid(((ICustomer)iCustomer).getCustomerUuid());
			util.insert(interaction);
		}
	}

    public static <E> void recordCustomersIntoOneRecord(Context context, ArrayList<E> iCustomers, int state){

        long now = System.currentTimeMillis();
        InteractionUtil util = InteractionUtil.getInstance(context);

        String comma = ",";
        StringBuilder sb = new StringBuilder();

        for(E iCustomer : iCustomers){
            sb.append(((ICustomer) iCustomer).getCustomerUuid() + comma);
        }
        String s = sb.toString();
        if(s.length() > 0){
            s = s.substring(0, s.length() - 1);
        }
        String userIdentity = String.valueOf(CustomerData.getCurrentUserIdentity());
        CustomerInteraction interaction = new CustomerInteraction();
        interaction.setDescription(s);
        interaction.setUpdateTime(now);
        interaction.setCategory(state);
        interaction.setUserIdentity(userIdentity);
        interaction.setUuid(UUID.randomUUID().toString());
        util.insert(interaction);
    }

    public static <E> void recordEveryCustomers(Context context, ArrayList<E> iCustomers, int state){

        if(iCustomers == null) return;

        long now = System.currentTimeMillis();
        InteractionUtil util = InteractionUtil.getInstance(context);
        String userIdentity = String.valueOf(CustomerData.getCurrentUserIdentity());

        CustomerInteractionDao dao = util.getTopicItemDao();
        int size = iCustomers.size();
        ArrayList<CustomerInteraction> interactions = new ArrayList<>(size);
        for(int i = 0; i < size; i++){
            CustomerInteraction interaction = new CustomerInteraction();
            interaction.setDescription("导入客户");
            interaction.setUpdateTime(now);
            interaction.setCategory(state);
            interaction.setUserIdentity(userIdentity);
            interaction.setUuid(UUID.randomUUID().toString());
            interaction.setCustomerUuid(((ICustomer)iCustomers.get(i)).getCustomerUuid());
            interactions.add(interaction);
        }
        dao.insertInTx(interactions);
    }


    public static void deleteCustomer(Context context, String customerUuid, boolean isImported){

        InteractionUtil util = InteractionUtil.getInstance(context);
        util.getTopicItemDao().queryBuilder().where(
                CustomerInteractionDao.Properties.CustomerUuid.eq(customerUuid))
                .buildDelete().executeDeleteWithoutDetachingEntities();

        if(isImported){
            QueryBuilder<CustomerInteraction> queryBuilder = util.getTopicItemDao().queryBuilder().where(
                    CustomerInteractionDao.Properties.Category.eq(7),
                    CustomerInteractionDao.Properties.UserIdentity.eq(String.valueOf(CustomerData.getCurrentUserIdentity())));

            List<CustomerInteraction> list = queryBuilder.list();
            if(list != null){
                for(CustomerInteraction ci : list){
                    if(ci != null && ci.getDescription() != null && ci.getDescription().contains(customerUuid)){
                        String newDescription = excludeOneItemInString(ci.getDescription(), customerUuid);
                        if(!compareIfEqual(newDescription, ci.getDescription())){
                            if(newDescription != null && newDescription.length()>0) {
                                ci.setDescription(newDescription);
                                util.getTopicItemDao().insertOrReplace(ci);
                            }else{
                                util.getTopicItemDao().queryBuilder().where(
                                        CustomerInteractionDao.Properties.Uuid.eq(ci.getUuid()))
                                        .buildDelete().executeDeleteWithoutDetachingEntities();
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    public static boolean compareIfEqual(String s1, String s2){
        if(s1 == null){
            if(s2 == null){
                return true;
            }else {
                return false;
            }
        }else{
            return s1.equals(s2);
        }
    }

    public static String excludeOneItemInString(String inputString, String excludeString){
        Matcher m = Pattern.compile(excludeString).matcher(inputString);

        if(m.find()){
            int start = m.start();
            int end = m.end();

            String s1 = inputString.substring(0,start);
            String s2 = inputString.substring(end);
            if(s1.length() > 0){
                s1 = s1.substring(0, s1.length() - 1);
            }else{
                if(s2.length()>0){
                    s2 = s2.substring(1, s2.length());
                }
            }
            return s1 + s2;
        }

        return inputString;
    }

	/**
	 * 用于记录动态
	 * @param context
	 * @param customerUuid
	 * @param state
	 * @param description
	 */
	public static void recordCustomer(Context context, String customerUuid, int state, String description){

		long now = System.currentTimeMillis();
		InteractionUtil util = InteractionUtil.getInstance(context);
        String userIdentity = String.valueOf(CustomerData.getCurrentUserIdentity());

		CustomerInteraction interaction = new CustomerInteraction();
		interaction.setDescription(description);
		interaction.setUpdateTime(now);
		interaction.setCategory(state);
		interaction.setUuid(customerUuid);//自己的uuid
		interaction.setCustomerUuid(customerUuid);//自己的uuid
        interaction.setUserIdentity(userIdentity);
		util.insert(interaction);
	}



}
